<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ProductSku extends Model
{
    use HasFactory;

    protected $fillable = [
        'title','on_sale','price','stock'
    ];

    protected $dates = [
        'on_sale' => 'boolean',//on_sale是布尔类型的数据
    ];

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function cartItems()
    {
        return $this->hasMany(CartItem::class);
    }

    public function attribute()
    {
        return $this->belongsToMany(Attribute::class,ProductSkuAttribute::class,'product_sku_id','attribute_id');
    }

    public function decreaseStock($amount)
    {
        if ($amount < 0){
            throw new \Exception('减库存不能小于0');
        }

        return $this->where('id',$this->id)->where('stock','>=',$amount)->decrement('stock',$amount);
    }

    public function addStock($amount)
    {
        if ($amount < 0){
            throw new \Exception('加库存不能小于0');
        }

        return $this->increment('stock',$amount);
    }
}
